import 'dart:convert';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:vischat/core/annotations/getx_route_enhanced.dart';

class EnhancedRouteGenerator extends GeneratorForAnnotation<GetXRoute> {
  @override
  Future<String> generateForAnnotatedElement(
    Element element,
    ConstantReader annotation,
    BuildStep buildStep,
  ) async {
    if (element is! ClassElement) return '';

    final imports = <String>{element.source.uri.toString()};

    // 收集中间件
    final middlewares = <String>[];
    for (final middleware in annotation.read('middlewares').listValue) {
      final type = middleware.toTypeValue();
      if (type != null) {
        middlewares.add(type.getDisplayString(withNullability: false));
        imports.addAll(await _findImportPaths(buildStep, type));
      }
    }

    // 处理单个binding
    String? binding;
    final bindingValue = annotation.read('binding');
    if (!bindingValue.isNull) {
      final type = bindingValue.typeValue;
      binding = type.getDisplayString(withNullability: false);
      imports.addAll(await _findImportPaths(buildStep, type));
    }

    return jsonEncode({
      'routeName': annotation.read('routeName').stringValue,
      'className': element.name,
      'imports': imports.where((i) => i.isNotEmpty).toList(),
      'middlewares': middlewares,
      'binding': binding,
    });
  }

  Future<Set<String>> _findImportPaths(
    BuildStep buildStep,
    DartType type,
  ) async {
    final element = type.element;
    if (element == null || element.source == null) return {};
    return {element.source!.uri.toString()};
  }
}
